<template>
  <view class="page">
		 <!-- @rightClick="save" -->
		<up-navbar @leftClick="back" title="管理分组" placeholder bgColor="#F2F1F6" :fixed="false" :titleStyle="titleStyle">
			<!-- <template #right>
				<span>保存</span>
			</template> -->
		</up-navbar>
		
		<!-- <view class="setGroupList">
		  <view v-for="(item, index) in tabs" 
		        :key="index" 
		        class="group-item"
		        :class="{ 'dragging': dragIndex === index }"
		        :style="getItemStyle(index)">
		    <view class="group-item-left" :style="{opacity: item.checked ? 1 : '0.3'}">
		      <span @click="onDel(item)">
		        <up-icon name="minus-circle-fill" color="red" size="20"></up-icon>
		      </span>
		      <span>{{item.title}}</span>
		    </view>
		    <view class="group-item-left" v-show="item.checked">
		      <span @click="goDetail(item)">
		        <up-icon name="edit-pen" size="20"></up-icon>
		      </span>
		      
		      <span 
		        @longpress="startDrag(index, $event)" 
		        @touchmove="onTouchMove" 
		        @touchend="endDrag">
		        <up-icon name="list" size="20"></up-icon>
		      </span>
		    </view>
		  </view>
		</view> -->
		
		<view class="setGroupList">
		  <view v-for="(item, index) in tabs"
		        :key="item.id"
		        class="group-item"
		        :class="{
		          'dragging': dragIndex === index && dragging,
		          'forbidden': forbiddenIndex === index
		        }"
		        :style="getItemStyle(index)">
		    <view class="group-item-left" :style="{opacity: item.checked ? 1 : '0.3'}">
		      <span @click="onDel(item)">
		        <up-icon name="minus-circle-fill" color="red" size="20"></up-icon>
		      </span>
		      <span>{{item.title}}</span>
		    </view>
		    <view class="group-item-left" v-show="item.checked">
		      <span @click="goDetail(item)">
		        <up-icon name="edit-pen" size="20"></up-icon>
		      </span>
		      <span @longpress="startDrag(index, $event)"
		            @touchmove="onTouchMove"
		            @touchend="endDrag">
		        <up-icon name="list" size="20"></up-icon>
		      </span>
		    </view>
		  </view>
		
		  <!-- 拖拽中的浮动节点 -->
		  <view v-if="dragging" 
		        class="dragging-item"
		        :style="dragStyle">
		    {{ tabs[dragIndex]?.title }}
		  </view>
		</view>

		

		<tui-modal :button="button" :show="modalShow" @click="modalClick" @cancel="modalShow = false"
		  :content="content"></tui-modal>
		
		<view class="add-btn">
			<up-button @click="goAdd" type="primary" text="新增分组"></up-button>
		</view>
  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat'
import { useUserStore } from '@/pinia-store/user'

export default {
  data() {
    return {
			titleStyle: {
				fontSize: '17px',
				fontWeight: '500',
			},
			cache: [
				{
						title: '全部',
						id: 0,
						checked: false
					},
					{
						title: '群聊',
						id: 1,
						checked: false
					},
					{
						title: '单聊',
						id: 2,
						checked: false
					},
				  {
				    title: '待办',
				    id: 3,
						checked: false
				  }
			],
			tabs: [],
			current: null,
			content: '确认删除分组？',
			modalShow: false,
			button: [{
			  text: "取消",
			  type: "gray",
			  plain: true
			},
			{
			  text: "确定",
			  type: "red",
			  plain: false
			}],
			dragIndex: -1,
			dragging: false,
			startY: 0,
			moveY: 0,
			itemHeight: 46,
			dragStyle: '',
			targetIndex: -1,
			forbiddenIndex: -1
    };
  },
  onLoad() {
		this.userInfo = useUserStore().user;
  	this.getGroup();
		
		uni.$on('addSave', () => {
			this.getGroup();
		})
  },
  methods: {
		startDrag(index, e) {
			this.dragIndex = index
			this.startY = e.touches[0].clientY
			this.moveY = this.startY
			this.dragging = true
			this.dragStyle = `top:${this.startY}px;`
		},
		onTouchMove(e) {
		  if (!this.dragging) return
		  this.moveY = e.touches[0].clientY
		  this.dragStyle = `top:${this.moveY}px;`
		
		  // 计算目标索引
		  let offset = this.moveY - this.startY
		  let targetIndex = this.dragIndex + Math.round(offset / this.itemHeight)
		
		  // 边界限制
		  if (targetIndex < 0) targetIndex = 0
		  if (targetIndex > this.tabs.length - 1) targetIndex = this.tabs.length - 1
		
		  // 🚫 上方墙限制：第四个元素（index=3）
		  if (targetIndex <= 3) {
		    targetIndex = 4
		  }
		
		  this.targetIndex = targetIndex
		},
		endDrag() {
		  if (!this.dragging) return
		  this.dragging = false
		
		  let finalIndex = this.targetIndex
		
		  // 上方墙限制
		  if (finalIndex <= 3) finalIndex = 4
		  // 下边界限制
		  if (finalIndex > this.tabs.length - 1) finalIndex = this.tabs.length - 1
		
		  // 执行交换
		  if (finalIndex !== this.dragIndex) {
		    const item = this.tabs.splice(this.dragIndex, 1)[0]
		    this.tabs.splice(finalIndex, 0, item)
		  }
		
		  this.dragIndex = -1
		  this.targetIndex = -1
			
			this.saveSort();
		},
		// 给正在拖动的item加样式
		getItemStyle(index) {
		  if (!this.dragging) return ''
		  if (index === this.dragIndex) {
		    return 'opacity:0;' // 原位置透明，用浮动层替代
		  }
		
		  // 挤兑逻辑，带动画
		  if (this.targetIndex > this.dragIndex &&
		      index > this.dragIndex && index <= this.targetIndex) {
		    return `transform: translateY(-${this.itemHeight}px); transition: transform 0.2s;`
		  }
		  if (this.targetIndex < this.dragIndex &&
		      index < this.dragIndex && index >= this.targetIndex) {
		    return `transform: translateY(${this.itemHeight}px); transition: transform 0.2s;`
		  }
		
		  return 'transform: translateY(0); transition: transform 0.2s;'
		},
		onDel(item) {
			if(!item.checked) return;
			this.current = item;
			this.modalShow = true;
		},
		async modalClick(index) {
			if(index === 0) return;
			let token = uni.getStorageSync('token')
			const params = {
				'data[account]': this.userInfo.chat_account,
				'data[token]': this.userInfo.token,
				'data[useId]': this.current.id,
				url: 'index.php/users/Group/DelGroupInfo'
			}

			const msg = await chatApi(this?.userInfo?.token || token, params)
			if(msg.code == 200) {
				this.modalShow = false;
				this.getGroup();
				uni.showToast({
					icon: 'none',
					title: '删除成功'
				})
			}else {
				uni.showToast({
					icon: 'none',
					title: '删除失败'
				})
			}
		},
		goDetail(item) {
			uni.navigateTo({
				url: `/pages/chat/list/addMsgGroup?id=${item.id}&title=${item.title}`
			})
		},
		goAdd() {
			uni.navigateTo({
				url: "/pages/chat/list/addMsgGroup"
			})
		},
		back() {
			uni.navigateBack();
		},
		async saveSort() {
			let token = uni.getStorageSync('token')

			const cache = this.tabs.slice(4, this.tabs.length-1);
			const params = {
				'data[account]': this.userInfo.chat_account,
				'data[token]': this.userInfo.token,
				'data[group_str]': JSON.stringify(cache),
				url: 'index.php/users/Group/ChangeGroupSort'
			}
			const msg = await chatApi(this?.userInfo?.token || token, params)
			
			if(msg.code == 200) {
				uni.showToast({
					icon: 'none',
					title: '修改成功',
					duration: 1500
				})
			}else {
				uni.showToast({
					icon: 'none',
					title: msg.info,
					duration: 1500
				})
			}
		},
		async getGroup() {
			let token = uni.getStorageSync('token')
			const params = {
				'data[account]': this.userInfo.chat_account,
				'data[token]': this.userInfo.token,
				'data[myAccount]': this.userInfo.chat_account,
				url: 'index.php/users/Group/GetGroupInfo'
			}
			
			const msg = await chatApi(this?.userInfo?.token || token, params);
			
			const cache = msg.data.map(item => {
				return {
					title: item.title,
					id: item.id,
					checked: item.checked
				}
			})
			this.tabs = [];
			this.tabs = [...this.cache, ...cache];
		},
  }
};
</script>

<style lang="scss" scoped>
	page {
		background-color: #F2F1F6;
	}
	.page {
	  width: 100%;
	  min-height: 100vh; /* 保证填满屏幕 */
	  background-color: #f5f5f5;
	}
	.setGroupList {
		position: relative;
		margin: 10px 10px 20px 10px;
		padding-bottom: 14px;
		border-radius: 8px;
		background-color: #fff;
		height: auto;
		.group-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 0 20px;
			font-size: 16px;
			line-height: 46px;
			border-bottom: 1rpx solid #edd;
			.group-item-left {
				display: flex;
				align-items: center;
			}
			span {
				margin: 0 4px;
			}
		}
		.group-item:last-child {
			border-bottom: none;
		}
	}
	.group-item {
	  transition: transform 0.2s;
	}
	.group-item.forbidden {
	  background-color: rgba(255, 0, 0, 0.2);
	  animation: shake 0.3s linear infinite;
	}
	
	@keyframes shake {
	  0%   { transform: translateX(0); }
	  25%  { transform: translateX(-4px); }
	  50%  { transform: translateX(4px); }
	  75%  { transform: translateX(-4px); }
	  100% { transform: translateX(0); }
	}
	
	.dragging-item {
	  position: fixed;
	  left: 20px;
	  right: 20px;
	  height: 46px;
	  line-height: 46px;
	  background: #fff;
	  border: 1px solid #ddd;
	  z-index: 999;
	  transform: scale(1.05);
	  box-shadow: 0 4px 10px rgba(0,0,0,0.15);
	  pointer-events: none;
	}
	.add-btn {
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		padding: 10px 20px 0 20px;
		width: 100%;
		height: 70px;
		background-color: #fff;
	}
</style>
